module Videre
   module JabberClient
     attr_accessor :jid
     def xmpp_connect
       Jabber::debug = true if $debug
       @jid=$config['xmpp']['jid']
       begin
         self.xmpp =Jabber::Client.new(Jabber::JID.new("#{@jid}/#{self.create_resource}"), false)
         self.xmpp.connect
         self.xmpp.auth($config['xmpp']['pass']) 
       rescue Errno::ECONNREFUSED
         self.log.notice "Cannot connect to XMPP server, connection refused"
         sleep 10
         retry
       end
       self.log.notice "Connected to XMPP server"
       self.add_callbacks
       self.set_status
     end

     def create_resource
       "videre_" + self.progname + "_" + `hostname`
     end

    # returns a full jid. If no arguments given it returns it's own full jid
    def full_jid(jid=@jid, resource=self.create_resource)
      full_jid="#{jid}/#{resource}" 
    end
 
    def set_status(show=nil, message="Ready to work")
      self.xmpp.send(Jabber::Presence.new.set_show(show).set_status(message))
    end

    def process_presence(pres)
      if pres.from != full_jid # No need to track my own instance
        self.contacts.update_item(pres)
      end
    end

    def process_message(message)
      if self.respond_to?("handle_message")
        self.send :handle_message, message
      else
        self.log.notice "Could not resolve :handle_message" if $debug
      end
    end
    
    def send_to_prog(progname, jid, message)
      online=Array.new 
      online=self.contacts.find_program(progname, jid)
      if online.size > 0
        self.deliver(online[0], message)
      else
        self.log.notice "Could not contact a available program named #{progname}" 
      end
    end

    def add_callbacks
      self.xmpp.add_presence_callback {  | pres |
        self.process_presence pres
      }
      self.xmpp.add_message_callback {  | message |
        self.process_message message
      }
    end
  end
end
